// import Vue from 'vue' //外部引入的形式不需要这个地方使用了
// import Vuex from 'vuex' //外部引入的形式不需要这个地方使用了
// Vue.use(Vuex) //外部引入的形式不需要这个地方使用了
import util from '@/utils/pro_util'
import { Loading } from 'element-ui';
import api from '@/HttpService/api';
import CMDUtil from '@/utils/im/CMDReverse';
import CMDPROTOCOL from '@/utils/im/CMD';
export default new Vuex.Store({
  state: {
    exptime: 0,
    CSRFToken: localStorage.getItem(process.env.PROJECT_NAME+"CSRFToken"),//这个是防御跨站脚本伪造令牌
    token: localStorage.getItem(process.env.PROJECT_NAME + "token"),//这个是服务器过期时间配置
    beforeLoginUrl: localStorage.getItem("beforeLoginUrl"),//登陆前访问的url
    beforeLoginTime: localStorage.getItem("beforeLoginTime"),//退出登陆前的时间
    pageInfo: null,//记录当前页面的url路径，标记翻页信息标记
    menuInfo: {menus: [], vertical: {key: "", keyPath: []}, horizontal: {key: "", keyPath: []}},//记录菜单激活状态
    loadingMap:{},//loading模板全局控制映射key:"请求的url",value为当前组建的id
    sysConfig:localStorage.getItem("sysConfig"),
    user:"",//用户信息配置
    userAsset:null,
    ws:null,
    cmdLen:5,
    HEARTBEAT_TIME:10000,
    CMD:CMDPROTOCOL,
    CMDHander:CMDUtil,
    currentToId:"",//当前的对话id
    currentToGroupId:"",//当前的对话组
    channels:[],//包含所有的客户端会话及本次会话的聊天记录，key为客户端cid ctx为字符串的数组；因为json不能自动侦听深度的属性变化。所以只能使用数组来做
  },
  getters: {
    getValForKey: (state) => (key) => {
      //根据key获取对应的信息
      // console.log(key,state[key]);
      return state[key];
    },
    getPageInfo: (state) => (url,findParams) => {
      // console.log("当前pegInfo对象",state.pageInfo);
      //获取当前组件的pageInfo信息
      if (state.pageInfo == null || state.pageInfo.url== null || state.pageInfo.url != url ) {
        return {
          "params": {
            "page": 1,//当前页码
            "rows": 15,//数据条数
            "orderBy": "",//排序参数
            "findParams": findParams==null?{}:findParams //筛选参数 [{"column":"数据库字段","condition":"条件标识符","value":"当前的值"}]
          },
          url:url,
          "pages": 0,//总页数
          "total": 0//总条数
        };
      } else {
        return state.pageInfo;
      }
    },
    getUserInfo: (state) => {
      if(state.user==""){
        return;
      }
      console.log(util.base64decode(state.user));
      return util.base64decode(state.user);
    },
    getConfig:(state) => (data)=> {
      // state.sysConfig = JSON.parse(localStorage.getItem("sysConfig"));
      return state.sysConfig;
    }
  },
  mutations: {
    saveUser(state,data){
      state.user = data;
      console.log(state.user);
    },
    saveAsset(state,data){
      console.log(data);
      state.userAsset = data;
    },
    minusUserAsset(state,obj){
      console.log(obj[0]);
      console.log(obj[1]);
      console.log(state.userAsset);
      if(obj[0]==1){
        state.userAsset.balance = state.userAsset.balance-obj[1];
      }else if(obj[0]==2){
        state.userAsset.coin = state.userAsset.coin-obj[1];
      }
      state.userAsset.updateTime = moment(new Date(obj[3]).getTime()).format('YYYY-MM-DD HH:mm:ss');
      console.log(state.userAsset);
    },
    plusUserFreezeAsset(state,obj){
      console.log(obj[0]);
      console.log(obj[1]);
      console.log(state.userAsset);
      if(obj[0]==1){
        state.userAsset.freezeBalance = state.userAsset.freezeBalance+obj[1];
      }else if(obj[0]==2){
        state.userAsset.freezeBalance = state.userAsset.freezeBalance+obj[1];
      }
      state.userAsset.updateTime = moment(new Date(obj[3]).getTime()).format('YYYY-MM-DD HH:mm:ss');
      console.log(state.userAsset);
    },
    saveToken(state, data) {
      //保存用户登录信息的token信息
      state.token = data;
      localStorage.setItem(process.env.PROJECT_NAME + "token", data);
    },
    saveConfig(state,data){
      state.sysConfig = data;
      localStorage.setItem("sysConfig", JSON.stringify(state.sysConfig));
    },
    updateToken(state, data) {
      //刷新当前session过期时间。
      if (state.token == null || state.token == undefined) {
        //可能出现一个页面上多个异步请求都触发了清除登录问题。所以这个地方做一个判断
        return;
      }
      var tmp_token = util.base64decode(state.token);
      tmp_token.exp = data.serviceTime + 3600000;//增加1小时的过期时间
      state.token = util.base64encode(JSON.stringify(tmp_token));
      localStorage.setItem(process.env.PROJECT_NAME + "token", state.token);
    },
    clearToken(state) {
      state.token = null;
      state.CSRFToken = null;
      state.user="";
      localStorage.removeItem(process.env.PROJECT_NAME + "token");
      localStorage.removeItem(process.env.PROJECT_NAME + "CSRFToken");
      state.currentToId="";
      state.currentToGroupId="";
      state.channels=[];
      if(state.ws){
        try {
          state.ws.close();
        }catch(err){
        }
      }
      state.ws=null;
    },
    saveBeforeLoginUrl(state, url) {
      localStorage.setItem("beforeLoginUrl", url);
      state.beforeLoginUrl = url;
      var time = new Date().getTime();
      localStorage.setItem("beforeLoginTime", time);
      state.beforeLoginTime = time;
    },
    savePageInfo(state, data) {
      state.pageInfo = data;
    },
    modifyMenuInfoActiveVertical(state, active) {
      // console.log(active);
      if (active !== undefined) {
        state.menuInfo.vertical.key = active.key
        state.menuInfo.vertical.keyPath = active.keyPath;
        state.menuInfo.horizontal = {key: "", keyPath: []}
      }
    },
    modifyMenuInfoActiveHorizontal(state, active) {
      if (active !== undefined) {
        state.menuInfo.horizontal.key = active.key
        state.menuInfo.horizontal.keyPath = active.keyPath;
        state.menuInfo.vertical = {key: "", keyPath: []}
      }
    },
    saveLoadingMap(state,obj){
      if(state.loadingMap[obj.target]==null){
        //存储loading模态
        state.loadingMap[obj.target?obj.target:'app']=Loading.service({
          target:"#"+(!obj.id?"app":obj.id),
          body:false,
          fullscreen:obj.id?true:false,
          lock:!obj.lock?false:true,
          text:!obj.text?"":obj.text,
          spinner:!obj.spiner?null:obj.spiner,
          background:!obj.background?"rgba(0,0,0,0.3)":obj.background
        });
      }
    },
    clearLoadingMap(state){
      for(var k in state.loadingMap){
        state.loadingMap[k].close();
        delete  state.loadingMap[k];
      }
    },
    init(state){
      api.getAllJson([
        // api.getJson(api.URLS.getMyAsset),
        api.getJson(api.URLS.getMemberUserBaseInfoVo),
        api.getJson(api.URLS.getAllSysConfig),
      ]).then((res) => {
        // state.userAsset =  res[0].data;
        state.user =  res[0].data;
        state.sysConfig = res[1].data;
        localStorage.setItem("sysConfig", JSON.stringify(state.sysConfig));
      }).catch(()=>{
      })
    },
    initws(state,wsurl){
      state.ws = new WebSocket(wsurl);
      state.ws.binaryType="arraybuffer";
    },
    windowopen(state,params){
      if(window.webViewJs2Java){
        webViewJs2Java.handlerWebViewParams(JSON.stringify(params));
      }
    }
  },
  actions: {
    init(context) {
      context.commit("init")
    },
  }
})
